<template>
    <view class="profile-container">
        <!-- 用户信息区域 -->
        <view class="user-info">
            <image class="avatar" :src="userInfo.avatarUrl" mode="aspectFill"></image>
            <text class="nickname">{{ userInfo.nickName }}</text>
        </view>

        <!-- 统计信息 -->
        <view class="stats-section">
            <view class="stats-item">
                <text class="stats-label">总积分</text>
                <text class="stats-value">{{ userInfo.totalScore || 0 }}</text>
            </view>
            <view class="stats-item">
                <text class="stats-label">胜率</text>
                <text class="stats-value">{{ userInfo.winningRate || 0 }}%</text>
            </view>
            <view class="stats-item">
                <text class="stats-label">总场次</text>
                <text class="stats-value">{{ userInfo.gamesCount || 0 }}</text>
            </view>
        </view>

        <!-- 房间操作按钮 -->
        <view class="room-actions">
            <button class="action-btn create" @click="createRoom">
                <text class="btn-icon">+</text>
                <text>创建房间</text>
            </button>
            <button class="action-btn scan" @click="scanToJoin">
                <text class="btn-icon">🔍</text>
                <text>扫码进房</text>
            </button>
        </view>

        <!-- 菜单列表 -->
        <view class="menu-list">
            <view class="menu-item" @click="handleMenuClick('history')">
                <text>对局记录</text>
                <text class="arrow">></text>
            </view>
            <view class="menu-item" @click="handleMenuClick('settings')">
                <text>设置</text>
                <text class="arrow">></text>
            </view>
        </view>

        <!-- 结算历史 -->
        <!-- <view class="history-section">
      <view class="section-title">结算历史</view>
      <view class="room-list">
        <view v-for="room in settledRooms" 
              :key="room.roomId" 
              class="room-card"
              @click="goToSettleDetail(room.roomId)">
          <view class="room-header">
            <text class="room-id">房间号：{{room.roomId}}</text>
            <text class="settle-time">{{formatTime(room.settleTime)}}</text>
          </view>
          <view class="members-preview">
            <view v-for="member in room.members" 
                  :key="member.openId" 
                  class="member-item">
              <image class="member-avatar" :src="member.avatar" mode="aspectFill"></image>
              <text class="member-score" :class="{'score-positive': member.score > 0, 'score-negative': member.score < 0}">
                {{member.score > 0 ? '+' : ''}}{{member.score}}
              </text>
            </view>
          </view>
        </view>
        <view v-if="settledRooms.length === 0" class="empty-tip">
          暂无结算记录
        </view>
      </view>
    </view> -->
    </view>
</template>

<script>
import eventBus from '@/utils/eventBus.js';
export default {
    data() {
        return {
            userInfo: {},
            roomInfo: null,
            settledRooms: [], // 已结算的房间列表
            page: 1,
            pageSize: 10,
            loading: false,
            hasMore: true,
        };
    },
    onShow() {
        console.log('个人中心页面加载');
        const userInfo = uni.getStorageSync('userInfo');
        if (!userInfo || !userInfo.openId) {
            console.log('未找到用户信息，跳转到授权页');
            uni.reLaunch({
                url: '/pages/auth/auth',
            });
            return;
        }
        this.userInfo = userInfo;
    },
    onPullDownRefresh() {
        this.page = 1;
        this.hasMore = true;
        this.loadSettledRooms().then(() => {
            uni.stopPullDownRefresh();
        });
    },
    onReachBottom() {
        if (this.hasMore && !this.loading) {
            this.page++;
            this.loadSettledRooms();
        }
    },
    methods: {
        getRoomInfo() {
            console.log('获取房间信息');
            // 每次获取最新的房间信息
            const roomInfo = uni.getStorageSync(`room_${this.userInfo.nickName}`);
            // 清除旧的房间信息
            this.roomInfo = null;
            if (roomInfo) {
                console.log('找到房间信息:', roomInfo);
                this.roomInfo = roomInfo;
            }
        },
        // 点击底部 tabBar 房间时的处理
        onTabItemTap(item) {
            if (item.pagePath.includes('index')) {
                if (!this.roomInfo) {
                    uni.showToast({
                        title: '请先创建房间',
                        icon: 'none',
                    });
                    return;
                }
            }
        },
        generateRoomId() {
            const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            let result = '';
            for (let i = 0; i < 6; i++) {
                result += chars[Math.floor(Math.random() * chars.length)];
            }
            return result;
        },
        //创建房间
        async createRoom() {
            try {
                // 检查房间是否存在 分别是加入的房间和自己创建的房间
                if (uni.getStorageSync('current_room_id')) {
                    uni.showToast({
                        title: '您已创建房间，不能重复创建！',
                        icon: 'none',
                    });
                    return;
                } else {
                    debugger;
                    if (uni.getStorageSync('scanned_room_id')) {
                        uni.showToast({
                            title: '您已经加入了房间，请您先结算！',
                            icon: 'none',
                        });
                        setTimeout(() => {
                            uni.switchTab({
                                url: '/pages/room/room',
                            });
                        }, 1000);
                        return;
                    }
                }
                // 生成6位随机房间号
                const roomId = this.generateRoomId();
                console.log('生成房间号:', roomId);
                // 调用云函数创建房间
                console.log('准备调用云函数，参数:', {
                    roomId,
                    userInfo: {
                        openId: this.userInfo.openId,
                        nickName: this.userInfo.nickName,
                        avatarUrl: this.userInfo.avatarUrl,
                    },
                });
                const result = await uniCloud.callFunction({
                    name: 'room',
                    data: {
                        action: 'create',
                        data: {
                            roomId,
                            ownerOpenId: this.userInfo.openId,
                            ownerName: this.userInfo.nickName,
                            createTime: new Date().getTime(),
                            updateTime: new Date().getTime(),
                            members: [
                                {
                                    openId: this.userInfo.openId,
                                    nickname: this.userInfo.nickName,
                                    avatarUrl: this.userInfo.avatarUrl,
                                    score: 0,
                                    joinTime: new Date().getTime(),
                                },
                            ],
                        },
                    },
                });
                console.log('创建房间结果:', result);
                if (result.result.code === 0) {
                    this.roomInfo = result.result.data;
                    // 存储当前房间ID
                    uni.setStorageSync('current_room_id', result.result.data.roomId);
                    console.log('创建房间成功，准备跳转');
                    // 跳转到房间
                    uni.switchTab({
                        url: '/pages/room/room',
                    });
                    uni.showToast({
                        title: '创建房间成功',
                        icon: 'success',
                    });
                } else {
                    throw new Error(result.result.msg);
                }
            } catch (e) {
                console.error('创建房间失败:', e);
                uni.showToast({
                    title: e.message || '创建房间失败',
                    icon: 'none',
                });
            }
        },
        //扫码登录小程序
        scanToJoin() {
            uni.scanCode({
                onlyFromCamera: true,
                scanType: ['qrCode'],
                success: res => {
                    console.log('扫码结果:', res);
                    // 检查是否为小程序码
                    if (res.scanType !== 'WX_CODE') {
                        uni.showToast({
                            title: '请扫描房间小程序码',
                            icon: 'none',
                        });
                        return;
                    }
                    // 检查扫码结果是否有效
                    const path = decodeURIComponent(res.path || '');
                    if (!path || !path.includes('scene=')) {
                        uni.showToast({
                            title: '无效的房间二维码',
                            icon: 'none',
                        });
                        return;
                    }
                    try {
                        // 从路径中提取scene参数
                        const scene = path.split('scene=')[1].split('&')[0]; // 处理可能存在的其他参数
						console.log(scene,'dddddd');
                        if (!scene) {
                            throw new Error('无效的房间ID');
                        }
                        // 直接加入房间
                        this.joinRoom(scene);
                    } catch (e) {
                        console.error('处理扫码结果失败:', e);
                        uni.showToast({
                            title: '无效的房间二维码',
                            icon: 'none',
                        });
                    }
                },
                fail: err => {
                    console.error('扫码失败:', err);
                    // 用户取消扫码不提示
                    if (err.errMsg.includes('cancel')) {
                        return;
                    }
                    uni.showToast({
                        title: err.errMsg || '扫码失败',
                        icon: 'none',
                    });
                },
            });
        },
        // 加入房间的具体逻辑
        async joinRoom(roomId) {
            // 检查房间是否存在
            // 获取房间信息
            const result = await uniCloud.callFunction({
                name: 'room',
                data: {
                    action: 'getRoom',
                    data: { roomId },
                },
            });
            console.log('获取房间结果:', result);
            if (result.result.code === 0) {
                this.roomInfo = result.result.data;
                try {
                    console.log('开始加载房间:', roomId);
                    const userInfo = uni.getStorageSync('userInfo');
                    if (!userInfo || !userInfo.openId) {
                        uni.reLaunch({
                            url: '/pages/auth/auth',
                        });
                        return;
                    }
                    // 检查用户当前房间
                    const currentRoomId = uni.getStorageSync('current_room_id');
                    const scannedRoomId = uni.getStorageSync('scanned_room_id');
                    if (!!currentRoomId || !!scannedRoomId) {
                        if (currentRoomId == roomId || scannedRoomId == roomId) {
                            uni.showToast({
                                title: '你已在该房间中',
                                icon: 'none',
                            });
                            uni.switchTab({
                                url: '/pages/room/room',
                            });
                        } else {
                            uni.showModal({
                                title: '提示',
                                content: '加入新房间将解散当前房间，是否继续？',
                                success: async res => {
                                    if (res.confirm) {
                                        try {
                                            // 结算当前房间
                                            await uniCloud.callFunction({
                                                name: 'room',
                                                data: {
                                                    action: 'settleRoom',
                                                    data: { roomId: currentRoomId },
                                                },
                                            });
                                            uni.setStorageSync('isScannedCode', roomId);
                                            uni.switchTab({
                                                url: '/pages/room/room',
                                            });
                                        } catch (e) {
                                            console.error('结算当前房间失败:', e);
                                            uni.showToast({
                                                title: '操作失败',
                                                icon: 'none',
                                            });
                                        }
                                    } else {
                                        uni.switchTab({
                                            url: '/pages/room/room',
                                        });
                                    }
                                },
                            });
                            return;
                        }
                    } else {
                        uni.setStorageSync('isScannedCode', roomId);
                        uni.switchTab({
                            url: '/pages/room/room',
                        });
                    }
                } catch (e) {
                    console.error('加载房间数据失败:', e);
                    uni.showToast({
                        title: e.message || '加载失败',
                        icon: 'none',
                    });
                }
            } else {
                uni.showModal({
                    title: '提示',
                    content: '该房间已解散',
                    showCancel: false,
                });
                return;
            }
        },
        handleMenuClick(type) {
            if (type == 'history') {
                uni.switchTab({
                    url: '/pages/payment/payment',
                });
            } else {
                // uni.({
                //   title: `${type}功能开发中`,
                //   icon: 'none'
                // });
            }
        },
        // async loadSettledRooms() {
        //   if (this.loading) return
        //   this.loading = true
        //   try {
        //     const result = await uniCloud.callFunction({
        //       name: 'room',
        //       data: {
        //         action: 'getSettledRooms',
        //         data: {
        //           page: this.page,
        //           pageSize: this.pageSize,
        //           openId: this.userInfo.openId
        //         }
        //       }
        //     })

        //     if (result.result.code === 0) {
        //       const rooms = result.result.data
        //       if (this.page === 1) {
        //         this.settledRooms = rooms
        //       } else {
        //         this.settledRooms.push(...rooms)
        //       }
        //       this.hasMore = rooms.length === this.pageSize
        //       console.log('加载结算房间成功:', rooms);
        //     }
        //   } catch (e) {
        //     console.error('加载结算房间失败:', e)
        //     uni.showToast({
        //       title: '加载失败',
        //       icon: 'none'
        //     })
        //   } finally {
        //     this.loading = false
        //   }
        // },
        goToSettleDetail(roomId) {
            uni.navigateTo({
                url: `/pages/settle/settle?roomId=${roomId}`,
            });
        },
        formatTime(timestamp) {
            const date = new Date(timestamp);
            return `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${String(date.getMinutes()).padStart(2, '0')}`;
        },
    },
};
</script>

<style>
.profile-container {
    padding: 40rpx;
}

.user-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 60rpx;
}

.avatar {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    margin-bottom: 20rpx;
    border: 4rpx solid #fff;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.nickname {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
}

.stats-section {
    display: flex;
    justify-content: space-around;
    margin-bottom: 40rpx;
}

.stats-item {
    text-align: center;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.stats-label {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 8rpx;
}

.stats-value {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
}

.room-actions {
    margin: 40rpx 0;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    gap: 20rpx;
}

.action-btn {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100rpx;
    border-radius: 50rpx;
    font-size: 32rpx;
    color: #fff;
    gap: 12rpx;
}

.action-btn::after {
    border: none;
}

.create {
    background-color: #07c160;
}

.scan {
    background-color: #409eff;
}

.btn-icon {
    font-size: 36rpx;
}

.menu-list {
    margin-top: 40rpx;
    background-color: #fff;
    border-radius: 16rpx;
    overflow: hidden;
}

.menu-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;
}

.menu-item:last-child {
    border-bottom: none;
}

.arrow {
    font-size: 28rpx;
    color: #666;
}

.history-section {
    padding: 30rpx;
}

.section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
}

.room-list {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
}

.room-card {
    background-color: #fff;
    border-radius: 16rpx;
    padding: 20rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
}

.room-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
}

.room-id {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
}

.settle-time {
    font-size: 24rpx;
    color: #999;
}

.members-preview {
    display: flex;
    flex-wrap: wrap;
    gap: 20rpx;
}

.member-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 8rpx;
}

.member-avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
}

.member-score {
    font-size: 24rpx;
    font-weight: 500;
}

.score-positive {
    color: #52c41a;
}

.score-negative {
    color: #ff4d4f;
}

.empty-tip {
    text-align: center;
    color: #999;
    font-size: 28rpx;
    padding: 40rpx 0;
}
</style>
